import { useState, useEffect, useRef } from "react";
import { categoryDelete, categoryGetOne, categoryGetTwo, categoryModify } from "@/api/modules/category";
import type { CategoryGetReturnItemModel } from "@/api/modules/category";
import type { FileItemModel } from "@/api/interface/index";

import { Button, Form, Input, message, Modal, Popconfirm, Space, Tag, Tree } from "antd";
import type { DataNode, TreeProps } from "antd/es/tree";
import { PlusOutlined, SearchOutlined } from "@ant-design/icons";
import "./index.less";
import CuploadImage, { CuploadImageMethods } from "@/components/CuploadImage";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/config/serviceLoading";
const categoryAdmin = () => {
	/** 初始化数据 */
	const [categoryData, setCategoryData] = useState<DataNode[]>([]);
	async function getList() {
		const { code: codeOne, data: categoryDataOne } = await categoryGetOne();
		const { code: codeTwo, data: categoryDataTwo } = await categoryGetTwo();
		if (codeOne === 0 && codeTwo === 0) {
			const newCategoryData = categoryDataOne.map(item => {
				let children: DataNode[] = [];
				categoryDataTwo.forEach(val => {
					if (item.id === val.parentId) {
						children.push({
							key: val.id,
							title: (
								<div className="flex justify-between">
									<span>{val.name}</span>
									<div>
										<Button
											type="text"
											size="small"
											style={{ color: "#ea64a2" }}
											onClick={e => {
												e.stopPropagation();
												openDialog(`修改分类—${val.name}`, "modify", "two", val, item.parentId);
											}}
										>
											修 改
										</Button>
										<Popconfirm
											placement="leftBottom"
											title="确定执行该操作吗？"
											onConfirm={() => openTips(val.id, "two")}
											okText="Yes"
											cancelText="No"
										>
											<Button
												type="text"
												size="small"
												danger
												onClick={e => {
													e.stopPropagation();
												}}
											>
												删 除
											</Button>
										</Popconfirm>
									</div>
								</div>
							),
							children: []
						});
					}
				});
				const itemData: DataNode = {
					title: (
						<div className="flex justify-between">
							<span>
								{item.name}
								<Tag className="!ml-20" color="processing">
									{children.length + 1}
								</Tag>
							</span>
							<div>
								<Button
									type="text"
									size="small"
									style={{ color: "#ea64a2" }}
									onClick={e => {
										e.stopPropagation();
										openDialog(`修改分类—${item.name}`, "modify", "one", item);
									}}
								>
									修 改
								</Button>
								<Button
									type="text"
									size="small"
									style={{ color: "#1890ff" }}
									onClick={e => {
										e.stopPropagation();
										openDialog(`新增子类—${item.name}`, "add", "two", item, item.id);
									}}
								>
									新增子类
								</Button>
								<Popconfirm
									placement="leftBottom"
									title="确定执行该操作吗？"
									onConfirm={() => openTips(item.id, "one")}
									okText="Yes"
									cancelText="No"
								>
									<Button
										type="text"
										size="small"
										danger
										onClick={e => {
											e.stopPropagation();
										}}
									>
										删除全部
									</Button>
								</Popconfirm>
							</div>
						</div>
					),
					key: `s${item.id}`, // 防止父子id会造成冲突，故前缀加上 s+Id
					children
				};
				return itemData;
			});
			setCategoryData(newCategoryData);
		}
	}
	/** 删除分类  */
	function openTips(id: number, className: string) {
		removeCategory(id, className);
	}
	async function removeCategory(id: number, className: string) {
		try {
			showFullScreenLoading();
			// 删除接口
			const { code, msg } = await categoryDelete({ id, className });
			if (code === 0) {
				message?.success(msg);
				getList();
			}
		} finally {
			tryHideFullScreenLoading();
		}
	}
	/** 模态框 */
	interface Dialog {
		visible: boolean;
		title: string;
		id?: string | number; // 不传或空为新增，传为修改
		parentId?: string | number; // 父级Id
		name: string;
		icon?: string;
		type: string; // 类型描述
		className: string; // 传one || two （一级或二级）
	}
	const [dialog, setDialog] = useState<Dialog>({
		visible: false,
		title: "",
		name: "",
		type: "",
		icon: "",
		className: ""
	});
	const [dialogLoading, setDialogLoading] = useState<boolean>(false);
	const [iconList, setIconList] = useState<FileItemModel[] | undefined>([]);
	const [form] = Form.useForm();
	const iconRef = useRef<CuploadImageMethods>(null);
	// 是否正在上传或存在上传失败的文件
	const [uploadLoading, setUploadLoading] = useState<boolean>(false);
	function openDialog(title: string, type: string, level: string, row?: CategoryGetReturnItemModel, parentId?: number | string) {
		// 打开模态框

		dialog.title = title;
		dialog.visible = true;
		dialog.className = level;
		dialog.parentId = parentId || "";
		console.log(row, "row");
		if (type === "modify") {
			dialog.icon = row?.icon ? row.icon[0].id.toString() : "";
			dialog.id = row!.id;
			dialog.name = row!.name;
			dialog.type = row!.type;

			// 修改的时候回显数据
			form.setFieldsValue({ name: row!.name, type: row!.type, icon: row?.icon ? row.icon[0].id.toString() : "" });
			setIconList(row!.icon);
		}
		console.log(dialog);
		setDialog({ ...dialog });
	}

	function closeDialog() {
		const newDialog = {
			visible: false,
			title: "",
			name: "",
			type: "",
			icon: "",
			className: "",
			id: undefined,
			parentId: undefined
		};
		setIconList([]);
		form.resetFields();
		// 清空文件列表
		iconRef.current && iconRef.current.clearFileList();
		setDialog(newDialog);
	}
	// 点击确定按钮
	const handleDialogOk = () => {
		if (uploadLoading) {
			message.warning("存在上传未完成或失败的图片，请检查后再提交！");
			return;
		}
		form.submit();
	};
	// 提交修改类别接口
	async function categoryModifyApi({ name, type, icon }: { name: string; type: string; icon: string }) {
		try {
			setDialogLoading(true);
			// 修改接口
			const { code, msg } = await categoryModify({
				className: dialog.className,
				name: name,
				type: type,
				id: dialog.id ? dialog.id : undefined,
				icon: icon || undefined,
				parentId: dialog.parentId ? dialog.parentId : undefined
			});
			if (code === 0) {
				message?.success(msg);
				getList();
				closeDialog();
			}
		} finally {
			setDialogLoading(false);
		}
	}
	// 提交新增/修改表单
	const onDialogFinish = async (form: any) => {
		console.log("form", form);
		categoryModifyApi({ name: form.name, type: form.type, icon: form.icon });
	};
	// 修改表单失败回调
	const onDialogFinishFailed = (errorInfo: any) => {
		message.warning("请检查表单填写是否正确！");
		console.log("Failed:", errorInfo);
	};
	// 文件上传状态回调
	function onStatusChange(status: string) {
		console.log(status, "status");
		setUploadLoading(status === "success" ? false : true);
	}
	// 文件上传回调
	function onChangeFormIds(name: string, ids: string[]) {
		console.log(name, ids);
		setDialog({ ...dialog, [name]: ids.toString() });
		form.setFieldValue(name, ids);
		form.validateFields([name]); // 触发表单验证
	}
	useEffect(() => {
		getList();
	}, []);
	return (
		<div className="categoryAdmin">
			<div className="categoryAdmin__title flex items-center justify-between mb-10">
				<Space className="flex items-center" size="large">
					<span className="text-18 font-bold">类别管理</span>
				</Space>
				<Space className="flex items-center">
					<Button
						icon={<PlusOutlined />}
						onClick={() => {
							openDialog("添加一级分类", "add", "one");
						}}
					>
						添加一级类别
					</Button>
					<Button
						type="primary"
						icon={<SearchOutlined />}
						onClick={() => {
							getList();
						}}
					>
						查询
					</Button>
				</Space>
			</div>
			<div className="categoryAdmin__content">
				<Tree treeData={categoryData} blockNode expandAction="click" />
			</div>
			<Modal
				width={600}
				title={dialog.title}
				open={dialog.visible}
				destroyOnClose={true}
				onOk={handleDialogOk}
				confirmLoading={dialogLoading}
				onCancel={closeDialog}
			>
				<Form
					form={form}
					preserve={false}
					size="middle"
					autoComplete="off"
					onFinish={onDialogFinish}
					onFinishFailed={onDialogFinishFailed}
				>
					{dialog.className !== "one" && (
						<Form.Item label="类别封面" name="icon" rules={[{ required: true, message: "请上传类别封面" }]}>
							<CuploadImage
								ref={iconRef}
								max={1}
								defaultFileList={iconList}
								onStatusChange={onStatusChange}
								onChangeIds={ids => onChangeFormIds("icon", ids)}
							/>
						</Form.Item>
					)}
					<Form.Item label="分类名称" name="name" rules={[{ required: true, message: "请输入分类名称" }]}>
						<Input placeholder="输入分类名称" maxLength={200} showCount />
					</Form.Item>
					<Form.Item label="类别描述" name="type" rules={[{ required: true, message: "请输入类别描述" }]}>
						<Input placeholder="输入类别描述" maxLength={200} showCount />
					</Form.Item>
				</Form>
			</Modal>
		</div>
	);
};

export default categoryAdmin;
